package com.fcy.teamwork.business.checkapply

import androidx.lifecycle.ViewModel
import cn.jpush.im.android.api.JMessageClient
import cn.jpush.im.android.api.model.Conversation
import cn.jpush.im.android.api.model.Message
import cn.jpush.im.api.BasicCallback
import com.fcy.teamwork.pojo.JobApply
import com.fcy.teamwork.pojo.JobApplyDetail
import com.fcy.teamwork.repo.RetrofitClient

class CheckApplyVM : ViewModel() {
    private val service: JobApplyService by lazy { RetrofitClient.getService() }
    suspend fun loadAllApply(): List<JobApplyDetail> {
        val allApplyWithMe = service.loadAllApplyWithMe()
        return if (allApplyWithMe.isOk) {
            allApplyWithMe.data
        } else {
            emptyList()
        }
    }

    suspend fun processApply(jobApply: JobApplyDetail): Boolean {
        val res = service.processApply(jobApply.jobApply).isOk
        if (res && jobApply.jobApply.isResolved == 1) {
            JMessageClient.addGroupMembers(
                jobApply.job.projectId.toLong(),
                listOf(jobApply.applicant.personId),
                object : BasicCallback() {
                    override fun gotResult(p0: Int, p1: String?) {
                        if (p0 == 0) {
                            val groupConversation =
                                Conversation.createGroupConversation(jobApply.job.projectId.toLong())
                            val textMsg =
                                groupConversation.createSendTextMessage("欢迎${jobApply.applicant.nikeName}加入！")
                            JMessageClient.sendMessage(textMsg)
                        }
                    }
                })
        }
        return res

    }
}